package com.rfy.framework.util;

import org.apache.commons.lang.StringUtils;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author zhanghuiyong
 * @创建时间 2019年04月17日
 * @描述: string工具类
 **/

public class StringUtil extends StringUtils {


    public static final String EMPTY_STRING = "";


    /**
     * 小说内容标签过滤
     *
     * @param oldContent 旧的字符串
     * @return
     */
    public static String novelContentDeleteStr(String oldContent) {
        //新笔趣阁标签去除
        //div
        String dellDiv1 = "<div id=\"content\">";
        String dellDiv2 = "<div class=\"read-content j_readContent\">";
        String dellDivMiaoJiang = "<div id=\"nr1\">";
        String dellDivXBQ6 = "<div id=\"content\">";
        String dellDivF1 = "</div>";
        // script
        String dellScript1 = "<script>";
        String dellScriptF1 = "</script>";
        //br
        String dellBr1 = "<br>";
        String dellBr2 = "<br />";
        String dellBrF1 = "</br>";
        //cha
        String dellCha = "chaptererror();";

        //p
        String dellP1 = "<p>";
        String dellPF1 = "</p>";

        //nbsp
        String dellNbsp = "&nbsp;";

        //&gt;
        String dellGt = "&gt;";

        String newContent = deleteSubString(oldContent, dellDivXBQ6,
                dellDiv2, dellGt, dellNbsp, dellBr1, dellBr2, dellBrF1, dellCha, dellDiv1, dellDivMiaoJiang, dellDivF1, dellScript1, dellScriptF1);
        return newContent;


    }

    /**
     * <p> 删除指定字符串 </p>
     *
     * @param str1
     * @param paramStr 被删除的字符串
     * @return
     * @其它信息
     */
    public static String deleteSubString(String str1, String... paramStr) {
        StringBuffer sb = new StringBuffer(str1);
        for (String s : paramStr) {
            while (true) {
                int index = sb.indexOf(s);
                if (index == -1) {
                    break;
                }
                sb.delete(index, index + s.length());
            }
        }
        return sb.toString();
    }

    /**
     * <p> 去除前n个字符 </p>
     *
     * @param origin 原字符串
     * @param count  去除字符串的个数
     * @return string 处理后的字符串
     * @其它信息
     */
    public static String truncateHeadString(String origin, int count) {
        if (origin == null || origin.length() < count) {
            return null;
        }
        char[] arr = origin.toCharArray();
        char[] ret = new char[arr.length - count];
        for (int i = 0; i < ret.length; i++) {
            ret[i] = arr[i + count];
        }
        return String.copyValueOf(ret);
    }

    /**
     * @param str
     * @param start 如果为正数，表示从前往后作为索引截取字符串；如果为负数，则表示从后往前作为索引截取字符串
     *              <p>
     *              若start+str.length<0,则从0开始截取字符串
     *              </p>
     * @return
     */
    public static String substring(String str, int start) {
        int iStart = start;
        if (str == null) {
            return null;
        }

        if (start < 0) {
            iStart = str.length() + start;
        }

        if (iStart < 0) {
            iStart = 0;
        }

        // FIX:当相等时，不必继续执行，提高效率 modified by WANGWENHU 2012-07-30
        if (iStart >= str.length()) {
            return EMPTY_STRING;
        }

        return str.substring(iStart);
    }

    /**
     * 字符拆分为数组，并返回包含条件的第一组字符串
     *
     * @param str       原字符串
     * @param split     分割字符串
     * @param condition 条件
     * @return
     */
    public static String getStrSplitByCondition(String str, String split, String condition) {
        String[] array = str.split(split);
        String result = "";
        for (int i = 0; i < array.length; i++) {
            if (array[i].contains(condition)) {
                return array[i];
            }
        }
        return result;
    }

    /**
     * 字符串拼接
     *
     * @param strArray
     * @return 拼接后的字符串
     */
    public static String join(String... strArray) {
        StringBuffer mStringBuffer = new StringBuffer();
        for (String str : strArray) {
            mStringBuffer.append(str);
        }
        return mStringBuffer.toString();
    }

    /**
     * 替换字符串
     *
     * @param strSc  需要进行替换的字符串
     * @param oldStr 源字符串
     * @param newStr 替换后的字符串
     * @return 替换后对应的字符串
     */
    public static String replace(String strSc, String oldStr, String newStr) {
        String ret = strSc;
        if (ret != null && oldStr != null && newStr != null) {
            ret = strSc.replaceAll(oldStr, newStr);
        }
        return ret;
    }

    /**
     * 分割字符串
     *
     * @param srcString
     * @param split
     * @return
     */
    public static String getSplitString(String srcString, String split) {
        StringBuilder stringBuilder = new StringBuilder(srcString);
        for (int i = 4; i < stringBuilder.length(); i += 5) {
            stringBuilder.insert(i, split);
        }
        return stringBuilder.toString();
    }


    public static boolean isContain(String strSc, String str, String splitStr) {
        String split = ",";
        if (!isNull(splitStr)) {
            split = splitStr;
        }
        if (!isNull(strSc, str)) {
            String[] strs = strSc.split(split);
            for (String newStr : strs) {
                if (newStr.trim().equals(str)) {
                    return true;
                }
            }
        }
        return false;
    }

    public static String subZeroAndDot(String s) {
        if (s.indexOf(".") > 0) {
            // 去掉多余的0
            s = s.replaceAll("0+?$", "");
            // 如最后一位是.则去掉
            s = s.replaceAll("[.]$", "");
        }
        return s;
    }

    /**
     * 判断数组是否为空
     *
     * @param strArray
     * @return
     */
    public static boolean isNull(String... strArray) {
        return strArray == null || strArray.length < 1;
    }

    /**
     * 判断数组是否为空
     *
     * @param strArray
     * @return
     */
    public static boolean isNotNull(String... strArray) {
        return !isNull(strArray);
    }

    /**
     * 判断参数每个元素是否都为空
     *
     * @param strArray
     * @return
     */
    public static boolean isAllEmpty(String... strArray) {
        boolean result = false;
        if (!isNull(strArray)) {
            for (String str : strArray) {
                if (isEmpty(str)) {
                    result = true;
                    break;
                } else {
                    result = false;
                }
            }
        }
        return result;
    }

    /**
     * 判断参数是否为空
     *
     * @param str
     * @return
     */
    public static boolean isEmpty(String str) {
        return str == null || ("").equals(str);
    }

    /**
     * 对象是否为空
     *
     * @param obj
     * @return
     */
    public static boolean isEmpty(Object obj) {
        return obj == null || "".equals(obj.toString());
    }

    /**
     * 判断参数是否不为空
     *
     * @param str
     * @return
     */
    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }

    /**
     * 替换字符串，修复java.lang.String类的replaceAll方法时第一参数是字符串常量正则时(如："address".
     * replaceAll("dd","$");)的抛出异常：java.lang.StringIndexOutOfBoundsException: String
     * index out of range: 1的问题。
     *
     * @param strSc  需要进行替换的字符串
     * @param oldStr 源字符串
     * @param newStr 替换后的字符串
     * @return 替换后对应的字符串
     */
    public static String replaceAll(String strSc, String oldStr, String newStr) {
        int i = -1;
        while ((i = strSc.indexOf(oldStr)) != -1) {
            strSc = new StringBuffer(strSc.substring(0, i)).append(newStr).append(strSc.substring(i + oldStr.length()))
                    .toString();
        }
        return strSc;
    }

    /**
     * 将字符串转换成HTML格式的字符串
     *
     * @param str 需要进行转换的字符串
     * @return 转换后的字符串
     * @since 1.1
     */
    public static String toHtml(String str) {
        String html = str;
        if (str == null || str.length() == 0) {
            return "";
        } else {
            html = replace(html, "&", "&amp;");
            html = replace(html, "<", "&lt;");
            html = replace(html, ">", "&gt;");
            html = replace(html, "\r\n", "\n");
            html = replace(html, "\n", "<br>\n");
            html = replace(html, "\"", "&quot;");
            html = replace(html, " ", "&nbsp;");
            return html;
        }
    }

    /**
     * 将HTML格式的字符串转换成常规显示的字符串
     *
     * @param str 需要进行转换的字符串
     * @return 转换后的字符串
     * @since 1.1
     */
    public static String toText(String str) {
        String text = str;
        if (str == null || str.length() == 0) {
            return "";
        } else {
            text = replace(text, "&amp;", "&");
            text = replace(text, "&lt;", "<");
            text = replace(text, "&gt;", ">");
            text = replace(text, "<br>\n", "\n");
            text = replace(text, "<br>", "\n");
            text = replace(text, "&quot;", "\"");
            text = replace(text, "&nbsp;", " ");
            text = replace(text, "&ldquo;", "“");
            text = replace(text, "&rdquo;", "”");
            return text;
        }
    }

    /**
     * 验证身份证号码
     *
     * @param idCard 居民身份证号码15位或18位，最后一位可能是数字或字母
     * @return 验证成功返回true，验证失败返回false
     */
    public static boolean checkIdCard(String idCard) {
        if (idCard.length() != 15 && idCard.length() != 18) {
            return false;
        }
        String regex = "[1-9]\\d{13,16}[a-zA-Z0-9]{1}";
        return Pattern.matches(regex, idCard);
    }


    /**
     * 格式化数字
     *
     * @param num (int)
     */
    public static String simpleFormat(int num) {
        DecimalFormat df = new DecimalFormat("#.#");
        StringBuilder numFormat = new StringBuilder();
        double numDouble;
        if (num > 1000 && num < 10000) {// 1千以上
            numDouble = num / 1000d;
            numFormat.append(df.format(numDouble)).append("k");
        } else if (num > 10000) { // 万以上
            numDouble = num / 10000d;
            numFormat.append(df.format(numDouble)).append("w");
        } else {
            numFormat.append(num);
        }
        return numFormat.toString();
    }

    /**
     * 数字转成以万、亿为单位，1.0-->1; 1.1-->1.1
     *
     * @param numStr (String)
     */
    public static String newNumFormat(String numStr) {
        try {
            long num = Integer.valueOf(numStr);
            return newNumFormat(num);
        } catch (Exception e) {
            e.printStackTrace();
            return numStr;
        }
    }

    /**
     * 数字转成以万、亿为单位，1.0-->1; 1.1-->1.1
     *
     * @param num (int)
     */
    public static String newNumFormat(long num) {
        DecimalFormat df = new DecimalFormat("#.#");
        StringBuilder numFormat = new StringBuilder();
        double numDouble;
        if (num <= 1000000 && num > 10000) { // 万以上
            numDouble = num / 10000d;
            numFormat.append(df.format(numDouble)).append("万");
        } else if (num > 1000000) { // 百万以上
            numDouble = num / 1000000d;
            numFormat.append(df.format(numDouble)).append("百万");
        } else {
            numFormat.append(num);
        }
        return numFormat.toString();
    }

    /**
     * 将一字符串数组以某特定的字符串作为分隔来变成字符串
     *
     * @param strs 字符串数组
     * @param sep  分隔字符串
     * @return 以token为分隔的字符串
     * @since 1.0
     */
    public static String join(String[] strs, String sep) {
        if (strs == null) {
            return null;
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < strs.length; i++) {
            if (i != 0) {
                sb.append(sep);
            }
            sb.append(strs[i]);
        }
        return sb.toString();
    }

    /**
     * 将一字符串以某特定的字符串作为分隔来变成字符串数组
     *
     * @param str   需要拆分的字符串("@12@34@56")
     * @param token 分隔字符串("@")
     * @return 以token为分隔的拆分开的字符串数组
     */
    public static String[] split(String str, String token) {
        String temp = str.substring(1, str.length());
        return temp.split(token);
    }

    /**
     * 验证字符串合法性
     *
     * @param str  需要验证的字符串
     * @param test 非法字符串（如："~!#$%^&*()',;:?"）
     * @return true:非法;false:合法
     * @since 1.0
     */
    public static boolean check(String str, String test) {
        if (isEmpty(str)) {
            return true;
        }
        boolean flag = false;
        for (int i = 0; i < test.length(); i++) {
            if (str.indexOf(test.charAt(i)) != -1) {
                flag = true;
                break;
            }
        }
        return flag;
    }


    public static long getLongValue(String strValue, long defaultValue) {
        if (!isNull(strValue)) {
            try {
                return Long.parseLong(String.valueOf(strValue));
            } catch (Exception e) {
            }
        }
        return defaultValue;
    }

    /**
     * 将数值型转换成字符串
     *
     * @param it  需要转换的Integer型值
     * @param ret 转换失败的返回值
     * @return 成功则返回转换后的字符串；失败则返回ret
     */
    public static String integer2String(Integer it, String ret) {
        try {
            return Integer.toString(it);
        } catch (NumberFormatException e) {
            return ret;
        }
    }

    /**
     * 比较两字符串大小(ASCII码顺序)
     *
     * @param str1 参与比较的字符串1
     * @param str2 参与比较的字符串2
     * @return str1>str2:1;str1<str2:-1;str1=str2:0
     * @since 1.1
     */
    public static int compare(String str1, String str2) {//
        if (str1.equals(str2)) {
            return 0;
        }
        int str1Length = str1.length();
        int str2Length = str2.length();
        int length = 0;
        if (str1Length > str2Length) {
            length = str2Length;
        } else {
            length = str1Length;
        }
        for (int i = 0; i < length; i++) {
            if (str1.charAt(i) > str2.charAt(i)) {
                return 1;
            }
        }
        return -1;
    }

    /**
     * 将字符串的首字母改为大写
     *
     * @param str 需要改写的字符串
     * @return 改写后的字符串
     * @since 1.2
     */
    public static String firstToUpper(String str) {
        return str.substring(0, 1).toUpperCase() + str.substring(1);
    }

    /**
     * list转String
     *
     * @param list
     * @param sign 分隔符号
     * @return
     */
    public static String list2String(List<String> list, String sign) {
        if (list == null || list.size() == 0) {
            return null;
        }
        StringBuffer sb = new StringBuffer();
        for (String string : list) {
            sb.append(string).append(sign);
        }
        return sb.substring(0, sb.length() - 1);
    }

    /**
     * String转list 去除null 空串
     *
     * @param target
     * @param sign   分隔符号
     * @return
     */
    public static List<String> string2List(String target, String sign) {
        List<String> usersList = new ArrayList<String>();
        if (!StringUtil.isEmpty(target)) {
            String[] vs = target.split(sign);
            for (String v : vs) {
                if (!StringUtil.isEmpty(v)) {
                    usersList.add(v);
                }
            }
        }
        return usersList;
    }

    public static String escapeHtmlSign(String value) {
        if (value == null) {
            return null;
        }

        if (value instanceof String) {
            String result = value;
            // "'<>&
            result = result.replaceAll("&", "&amp;").replaceAll(">", "&gt;").replaceAll("<", "&lt;")
                    .replaceAll("\"", "&quot;").replaceAll("'", "&#39;");
            return result;
        } else {
            return value;
        }
    }

    public static String unEscapeHtmlSign(String value) {
        if (value == null) {
            return null;
        }

        if (value instanceof String) {
            String result = value;
            // "'<>&
            result = result.replaceAll("&amp;", "&").replaceAll("&gt;", ">").replaceAll("&lt;", "<")
                    .replaceAll("&quot;", "\"").replaceAll("&#39;", "'");
            return result;
        } else {
            return value;
        }
    }


    /**
     * 将浮点数进行四舍五入
     *
     * @return 改写后的字符串
     */
    public static String doubleToString(double str) {
        return doubleToString(str, 2);
    }

    public static String formatNum(float num) {
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        return decimalFormat.format(num);
    }

    public static String numToString(int str) {
        return doubleToString(str, 2);
    }

    public static String doubleToString(double str, int offset) {
        return new BigDecimal(str + "").setScale(offset, BigDecimal.ROUND_HALF_UP).toString();
    }

    public static Date stringDateTodate(String date) {
        String time = date.substring(6, date.length() - 7);
        return new Date(Long.parseLong(time));
    }

    /**
     * 截取指定长度 从0开始，包左不包右
     */
    public static String spliteTime(String dateStr, int start, int end) {
        CharSequence sequence = dateStr.subSequence(start, end);
        return sequence.toString();
    }

}
